﻿// Jinx AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using Jinx.Applications;

namespace Jinx.Communications.Applications.Services
{
    public class ServiceHost : ContextualServer
    {
        private static readonly Regex ActionPattern;

        static ServiceHost()
        {
            ActionPattern = new Regex(@"^(.*)\." + Extensions.Action + '$');
        }

        public ServiceHost(ApplicationContextManager ApplicationContextManager)
            : base(ApplicationContextManager)
        {
        }

        #region IServer ContextualServer

        protected override void ProcessRequest(HttpListenerContext Context, string RelativePath,
                                               ApplicationContext ApplicationContext)
        {
            var ControllerPath = ControllerPathFromRelativePath(RelativePath);
            var Action = ActionFromRelativePath(RelativePath);
            var Argument = GetRequestBody(Context);

            var Controller = ApplicationContext.ControllerContext.ResolveController(ControllerPath);

            var ReturnValue = OperationInvocation.Invoke(Action, Controller, Argument);

            DoResponse(Context, 200, new ResponseObject(ReturnValue));
        }

        #endregion

        public static IEnumerable<string> ControllerPathFromRelativePath(string RelativePath)
        {
            var Parts = RelativePath.Split('/');

            return Parts.Take(Parts.Length - 1);
        }

        public static string ActionFromRelativePath(string RelativePath)
        {
            var Parts = RelativePath.Split('/');
            var Action = Parts[Parts.Length - 1];

            var ActionMatch = ActionPattern.Match(Action);

            if (ActionMatch.Success)
                return ActionMatch.Groups[1].Value;
            
            throw new Exception(Action + " is not a valid name for an action");
        }
    }
}